/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.io.File;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.widget.Toast;

import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.IOUtilities;
import com.phonebooksharing.android.util.LocationUtil;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.GenericTransferDTO;
import com.phonebooksharing.dto.ReturnItem;
import com.phonebooksharing.dto.gallery.PostCardItem;

public class SendPostcardMessageTask extends NetworkHandlerTask<String, Void, Boolean> {
    private ProgressDialog progress;
    private Context cx;
    protected PostCardItem pcMsg;
    private ArrayList<Integer> groupList;
    
    public SendPostcardMessageTask(Context cx, ArrayList<Integer> groupList) {
        this.cx = cx;
        this.groupList = groupList;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        
        progress = new ProgressDialog(cx);
        progress.setTitle("Processing");
        progress.setMessage("Please wait while we post your message...");
        progress.setIndeterminate(true);
        progress.setCancelable(false);
        progress.show();
    }

    @Override
    protected Boolean doInBackground(String... texts) {
        
        boolean isOK = false;
        pcMsg = new PostCardItem();
        try {
            pcMsg.title    = "New Post Card";
            pcMsg.when     = GeneralUtils.getGmtTimeInMilis();
            
            Location l = LocationUtil.getCurrentLocation(cx);
            pcMsg.latitude      = l.getLatitude();
            pcMsg.longitude     = l.getLongitude();
            pcMsg.postLatitude  = "" + pcMsg.latitude;
            pcMsg.postLongitude = "" + pcMsg.longitude;
            pcMsg.whereAt       = LocationUtil.getWhereAt(cx);
            
            GenericTransferDTO g = new GenericTransferDTO();
            g.authItem   = Global.authItem;
            g.simpleItem = pcMsg;
            
            String url = String.format(Global.MESSAGE_SERVLET_URL, "cpc" /*ac*/, "c" /*t*/, "" /*q*/, "" /*mt*/);
            PostCardItem pc = (PostCardItem)doNetworkPost(url, g);
            pc.mimeType = "image/jpeg";

            File temp = IOUtilities.getExternalFile(System.currentTimeMillis() + ".tmp");
            IOUtilities.storeExternalBitmap(Global.postCardFront.getBitmap(), temp);
            url = String.format("http:" + Global.MESSAGE_SERVLET_URL, "cpc" /*ac*/, "uf" /*t*/, pc.postcardID /*q*/, pc.mimeType /*mt*/);
            GalleryUtilities.uploadBinaryStream(url, temp);
            temp.delete();
            
            temp = IOUtilities.getExternalFile(System.currentTimeMillis() + ".tmp");
            IOUtilities.storeExternalBitmap(Global.postCardBack.getBitmap(), temp);
            url = String.format("http:" + Global.MESSAGE_SERVLET_URL, "cpc" /*ac*/, "ub" /*t*/, pc.postcardID /*q*/, pc.mimeType /*mt*/);
            GalleryUtilities.uploadBinaryStream(url, temp);
            temp.delete();
            
            url = String.format(Global.MESSAGE_SERVLET_URL, "cpc" /*ac*/, "d" /*t*/, "" /*q*/, "" /*mt*/);
            g.simpleItem = pc;
            g.items2     = groupList;
            ReturnItem ri = (ReturnItem)doNetworkPost(url, g);
            
            isOK = ri.isOK();
        } catch (Exception e) {
            e.printStackTrace();
            isOK = false;
        }
//        if(!isOK) {
//            PhonebookSharingManager.addMsgSync(cx,
//                  voiceMsg.title,
//                  voiceMsg.text,
//                  Message.MSG_TYPE_TEXT);
//        }
//        
        return isOK;
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        progress.dismiss();
        if(result) {
            Toast.makeText(cx, "Your message has been send successfully!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(cx, "It was not possible to deliver your message.\n\nPlease try it again...", Toast.LENGTH_LONG).show();
        }
    }
}